/**
 * 工具
 * 2019-07-12
 */
window.webSocketCtrl=new Array();
let electron=null;
try {
	electron=window.nodeElectron=require('electron');
} catch (error) {
	electron =window.parent.nodeElectron;
}

//国际化空白方法
$.i18n = {
	propJsp : function(str){
		return str;
	}
}


//重写localStorage/session
let hrefUrl=window.document.location.href;
localStorage.setItem = function(key,value){
	electron.ipcRenderer.send('setItem',key,value);
}
sessionStorage.setItem=function(key,value){
	electron.ipcRenderer.send('setItem',hrefUrl+key,value);
}

localStorage.removeItem = function(key){
	electron.ipcRenderer.send('removeItem',key);
}
sessionStorage.removeItem = function(key){
	electron.ipcRenderer.send('removeItem',hrefUrl+key);
}

localStorage.getItem=(key)=>{
	let result=electron.ipcRenderer.sendSync('getItem',key);
	if(result.length>0){
		return result[0].value;
	}else{
		return null;
	}
}
sessionStorage.getItem=(key)=>{
	let result=electron.ipcRenderer.sendSync('getItem',hrefUrl+key);
	if(result.length>0){
		return result[0].value;
	}else{
		return null;
	}
}

//服务端地址
$.HSAPI_SERVER="192.168.1.156:8080";
//服务端包名
$.HSAPI_PACKAGENAME="huasheng";

//获取
let configValue=electron.ipcRenderer.sendSync('getConfigMess');
$.HSAPI_APPCUSTOMPATH = configValue.appCustomPath
if(configValue.HSAPI_SERVER!='')
	$.HSAPI_SERVER=configValue.HSAPI_SERVER;
if(configValue.HSAPI_PACKAGENAME!='')
	$.HSAPI_PACKAGENAME=configValue.HSAPI_PACKAGENAME; 

//jquery扩展类方法
let HSAPI_SERVER_N=$.HSAPI_SERVER.split("://")[1];
$.extend({
	//应用请求地址
	HSAPI_AJAXURL : $.HSAPI_SERVER+"/"+$.HSAPI_PACKAGENAME,
	HSAPI_URL : HSAPI_SERVER_N+"/"+$.HSAPI_PACKAGENAME,
	HSAPI_RPTURL : ($.HSAPI_SERVER.indexOf("https")>-1?"hsrpts":"hsrpt")+":"+HSAPI_SERVER_N+"/"+$.HSAPI_PACKAGENAME,
	HSAPI_SERVICEIP : HSAPI_SERVER_N,
	HSAPI_BILLURL : ($.HSAPI_SERVER.indexOf("https")>-1?"hsrpts":"hsrpt")+":"+HSAPI_SERVER_N+"/"+$.HSAPI_PACKAGENAME+"/hobill/bill?&token="+(localStorage.getItem('token')||'')+"&hotelId="+(localStorage.getItem('hotelId')||''),//+"JSESSIONID=028A61A420BF5FBAE49F665C0D8AC741",
	HSAPI_PROCEDUREGRID : "/qms/mobile/proceduregrid", 
	HSAPI_PROCEDURE : "/qms/mobile/procedure",
	HSAPI_PROCEDURE2_LIST : "/qms/mobile/procedure2",
	HSAPI_PROCEDURE2POST : "/qms/mobile/procedure2Post",
	HSAPI_PROCEDURE2_PASS : "/qms/mobile/procedure2bypass",
	HSAPI_PROCEDURE3 : "/qms/mobile/procedure3",
	HSAPI_PROCEDURE4 : "/qms/mobile/procedure4", 
	//返回按钮通用方法 区分关闭页 还是TAB标签的
	HSAPI_CLOSEWINDOW_TAB : function(){
		// debugger
		var js = $.HSAPI_URLPRAMS();
		if(js.open_type&&js.open_type==1){
			var $li = $(window.frameElement).closest("#indexMenuContent").find("ul[role=tablist]").find("li");
			var $ul = $(window.frameElement).closest("#indexMenuContent").find("ul[role=tablist]");
			var size = $li.size();
			var index = $ul.find("li").index($ul.find("li.active"));
			var $div = $(window.frameElement).closest("#indexMenuContent").find("ul[role=tablist]").next();
			$div.find(".tab-pane.content.active").removeClass("active")
			if((index+1)==size){
				$ul.find("li:first").find("a").tab("show");
				$div.find(".tab-pane.content").eq(0).addClass("active");
			}else{
				$ul.find("li.active").next().find("a").tab("show");
				$div.find(".tab-pane.content").eq(index+1).addClass("active");
			}
		}else{
			self.close();
		}
	},
	//AJAX请headers
	HSAPI_HEADERS:{
		hotelId : localStorage.getItem('hotelId')||'',
		app : "pmsbusiness",
		bmh : localStorage.getItem('bmh')||"",
		token :localStorage.getItem('token')||"",
	},
	//当前登录用户
	HSAPI_USERID : "",
	//当前登陆用户
	HSAPI_USER:function(){
		return "L01";
	},
	//获取当前网址，如： http://localhost:8081/index#business/homepage
	HSAPI_CURPATH:function(){
		return window.document.location.href;
	},
	//获取主机地址之后的目录，如： /index
	HSAPI_PATHNAME:function(){
	    return window.document.location.pathname;
	},
	//获取主机地址，如： localhost:8081
	HSAPI_LOCALHOSTPATH:function(){ 
	    return window.location.host;
	},
	//获取带"/"的项目名，如：例子中为空字符串
	HSAPI_PROJECTNAME:function(){
		var pathName = document.location.pathname;
		var index = pathName.substr(1).indexOf("/");
		return pathName.substr(0, index + 1);
	},
	//获取端口号，如：8081
	HSAPI_PORT:function(){
		return window.location.port;
	},
	//获取协议，如：http:
	HSAPI_PROTOCOL:function(){
		return window.location.protocol;
	},
	//获取#开始的锚，如：#business/homepage
	HSAPI_HASH:function(){
		return window.location.hash;
	},
	HSAPI_GETVERSION:function(){
		var package = require("../../package.json");
		return package.version;
	},
    HSAPI_GETNOWDATE:function(){
        function getNow(s) {
            return s < 10 ? '0' + s: s;
        }
            
        var myDate = new Date();            
            
        var year=myDate.getFullYear();        //获取当前年
        var month=myDate.getMonth()+1;   //获取当前月
        var date=myDate.getDate();            //获取当前日
            
            
        var h=myDate.getHours();              //获取当前小时数(0-23)
        var m=myDate.getMinutes();          //获取当前分钟数(0-59)
        var s=myDate.getSeconds();
            
        var now=year+'-'+getNow(month)+"-"+getNow(date)+" "+getNow(h)+':'+getNow(m)+":"+getNow(s);
        return now
    },
	//获取url参数JSON
	HSAPI_URLPRAMS:function(){
		var url = $.HSAPI_HASH();
	    var params = new Object();
	    if (url.indexOf("?") != -1) {
	        var str = url.split("?")[1];
	        var strs = str.split("&");
	        for (var i = 0; i < strs.length; i++) {
	            params[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
	        }
	    }
	    return params;
	},
	//获取指定url参数
	HSAPI_URLPRAM:function(name){
		var url = $.HSAPI_HASH();
	    if (url.indexOf("?") != -1) {
	        var str = url.split("?")[1];
	        var strs = str.split("&");
	        for (var i = 0; i < strs.length; i++) {
	        	if(strs[i].split("=")[0]===name)
	        		return unescape(strs[i].split("=")[1]);
	        }
	    }
	    return null;
	},
	//判断是否为JSON
	HSAPI_ISJSON:function(str){
		if (typeof str == 'string') {
	        try {
	            var obj=JSON.parse(str);
	            if(typeof obj == 'object' && obj ){
	                return true;
	            }else{
	                return false;
	            }
	        } catch(e) {
	            return false;
	        }
	    }
	    console.log('判断是否为JSON参数必须为String');
	},
	//格式化JSON字符串
	HSAPI_FORMATJSON:function(json,options){
		var reg = null,
        formatted = '',
        pad = 0,
        PADDING = '    ';
	    options = options || {};
	    options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
	    options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
	    if (typeof json !== 'string') {
	        json = JSON.stringify(json);
	    }
	    if(!$.HSAPI_ISJSON(json))
	    	return "不合法的JSON格式字符串";
	    json = JSON.parse(json);
	    json = JSON.stringify(json);
	    reg = /([\{\}])/g;
	    json = json.replace(reg, '\r\n$1\r\n');
	    reg = /([\[\]])/g;
	    json = json.replace(reg, '\r\n$1\r\n');
	    reg = /(\,)/g;
	    json = json.replace(reg, '$1\r\n');
	    reg = /(\r\n\r\n)/g;
	    json = json.replace(reg, '\r\n');
	    reg = /\r\n\,/g;
	    json = json.replace(reg, ',');
	    if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
	        reg = /\:\r\n\{/g;
	        json = json.replace(reg, ':{');
	        reg = /\:\r\n\[/g;
	        json = json.replace(reg, ':[');
	    }
	    if (options.spaceAfterColon) {
	        reg = /\:/g;
	        json = json.replace(reg, ': ');
	    }
	    $.each(json.split('\r\n'), function(index, node) {
	        var i = 0,
	            indent = 0,
	            padding = '';
	
	        if (node.match(/\{$/) || node.match(/\[$/)) {
	            indent = 1;
	        } else if (node.match(/\}/) || node.match(/\]/)) {
	            if (pad !== 0) {
	                pad -= 1;
	            }
	        } else {
	            indent = 0;
	        }
	        for (i = 0; i < pad; i++) {
	            padding += PADDING;
	        }
	        formatted += padding + node + '\r\n';
	        pad += indent;
	    });
        return formatted;
	},
	//提示
	HSAPI_ALERT:function(MSG,status,callBack){
		var color="red";
		if(status&&status==="success")
			color="green";
		var showDiv='<h3 class="header smaller lighter '+color+'">'+
					   	'<i class="ace-icon fa fa-bullhorn"></i>'+MSG+
				   	 '</h3>';
		bootbox.dialog({
			message: showDiv,
			onEscape:true,
			buttons: 			
			{
				"button" :
				{
					"label" : " 确定 ",
					"className" : "btn-sm",
					"callback": callBack?callBack:function(){}
				},
			}
		});
	},
	//获取当前时间
	HSAPI_TIME:function(type="24"){
		var date=new Date();
		var time=date.toLocaleTimeString('chinese', { hour12: (type==="24"?false:true) }).replace(/^\D*/,''); 
		return time;
	},
	//获取当前日期
	HSAPI_DATE:function(type=""){
		var nowDate = new Date();
		var year = nowDate.getFullYear();
		var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
		  : nowDate.getMonth() + 1;
		var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
		  .getDate();
		return year + type + month + type + day;
	},
	//构造查询参数
	HSAPI_ASKJSONINFO:function(jsonstr,fu,jsonstr2,jsonstr3,jsonstr4 ,jsonstr5){
		return {"fu":fu,"jn":jsonstr,"jnJson2":jsonstr2,"jnJson3":jsonstr3,"jnJson4":jsonstr4,"jnJson5":jsonstr5};
	},
	HSAPI_HOLOGIN:function(hotelId,bmh,userid,upass,jn,jnJson2,fu,success,error){
		$.HSAPI_HEADERS.hotelId = hotelId;
		$.HSAPI_HEADERS.bmh = bmh;
		$.HSAPI_HEADERS.token="";
		$.HSAPI_USERID = userid;
		jQuery.ajax({   
			type : 'POST',
			url : $.HSAPI_AJAXURL+"/qms/mobile/login",      
			dataType : 'json',
			async: false,
			headers : $.HSAPI_HEADERS, 
			data:{
				"userid":"L01",
				// "upass":upass,
				"jn":JSON.stringify(jn),
				"bmh" : bmh,
				"jnJson2":JSON.stringify(jnJson2),
				"fu":"HoLogin"
			},
			success : function(data) {
				success(data);
			},
			error  :function(data){
				error(data);
			}
		})
	},
	HSAPI_CALLPROCEDURE2 : function(arg1,procedure,arg2,success,error,list){
		jQuery.ajax({   
			type : 'POST',
			url : $.HSAPI_AJAXURL+"/qms/mobile/procedure2",      
			dataType : 'json',
			headers : $.HSAPI_HEADERS, 
			data:$.HSAPI_ASKJSONINFO(JSON.stringify(arg1),procedure,JSON.stringify(arg2),list||""),
			success : function(data) {	
				success(data);
			},
			error  :function(data){
				error(data);
			}
		})
	},
	//新开模态
	HSAPI_NEWMODAL:function(url,params={},callBack){
		let defaultParams={
			width:800,
			height:600,
			title:'新建模态',
			parentId:electron.remote.getCurrentWindow().id,
			frame:true,
		};
		params=$.extend({},defaultParams,params);
		electron.ipcRenderer.send('newModal',{'hash':url},params);

		electron.ipcRenderer.removeAllListeners('callBackNewModal');
		electron.ipcRenderer.on('callBackNewModal', function(event, message) {
			callBack(message);
		});
	},
	//新开窗口
	HSAPI_NEWWINDOW:function(params={},hash){
		let url='./indexWindow.html';
		let options={'hash':hash};
		let defaultParams={
			top:$("#sidebar").height(),
			left:0,
			title:'新建窗口',
			parentId:electron.remote.getCurrentWindow().id,
			menuCode:'',
			parentMenuCode:''
		};
		params=$.extend({},defaultParams,params);
		electron.ipcRenderer.send('newWindow',url,params,options);
	},
    HSAPI_NEWWINDOW_SELF:function(params={},url){
        import('../jquery.moudles.detail.js?'+Math.random()).then(data=>{
            let moudles=data.moudles,moudlesFilter=[],urlHash=url;
            Object.keys(moudles).forEach(key => {
                if(urlHash.indexOf(key)>-1){
                    moudlesFilter=[...moudles[key]];
                }
            });
            moudlesFilter.map((v,k)=>{
                $.extend({
                    [v.moudle]:()=>{
                        return import(`${"."+v.path}`);
                    }
                });
            });
        }).then(()=>{
            window.location.href = url
        });
    },
	//已打开窗体控制
	HSAPI_WINDOWOPEN:function(){
		electron.ipcRenderer.removeAllListeners('windowOper');
		electron.ipcRenderer.on('windowOper', function(event, message) {
			$.indexMenu.windowOpen(message);
		});
	},
	//获取主进程传递的参数
	HSAPI_GETPAGEPARAMS:function(callBack){
		electron.ipcRenderer.on('dataJsonPort', function(event, message) {
			if(message.hasOwnProperty('title'))
				document.title=message.title;
			callBack(message);
		});
	},
	//模态回调父窗体
	HSAPI_CALLBACK_MODAL:function(message){
		let currentWindow=electron.remote.getCurrentWindow();
		if(currentWindow.isModal){
			let id=currentWindow.getParentWindow().id;
			electron.ipcRenderer.sendTo(id,'callBackNewModal',message);
		}else{
			alert('未完待续');
		}
	},
	//关闭模态
	HSAPI_CLOSEMODAL:function(){
		electron.remote.getCurrentWindow().close();
	},
	//设置模态大小
	HSAPI_SETMODALSIZE:function(width,height,center){
		let win = electron.remote.getCurrentWindow();
		let arr = win.getSize();
		if(!width){
			width = arr[0]
		}
		if(!height){
			height = arr[1]
		}
		electron.remote.getCurrentWindow().setContentSize(width,height);

        if(center){
			electron.remote.getCurrentWindow().center()
		}
        
	},
	//设置快捷键(当前窗体)
	HSAPI_SETSHORTCUTKEY:function(callBack){
		window.addEventListener('keyup', (e)=>{
            callBack(e);
        }, true)
	},
	//自动检查更新
	HSAPI_UPDATEAUTO:function(callBack){
		let remote=electron.remote;
		let dialog=electron.remote.dialog;
		electron.ipcRenderer.send("checkForUpdate");
		electron.ipcRenderer.removeAllListeners('message');
		electron.ipcRenderer.on("message", (event, text,info) =>{
			let win=remote.getCurrentWindow(); 
			if(text=='-1'){
				// dialog.showMessageBox(win, {
				// 	type: 'error',
				// 	title: '错误',
				// 	message: '获取更新失败',
				// 	buttons: ['知道了']
				// }).then((index) => {
				// 	return;
				// });
				callBack('-1');
			}
            if(text=='1'){
				callBack('1');

				// dialog.showMessageBox(win, {
				// 	type: 'info',
				// 	title: '更新',
				// 	message: '检测到新版本:'+info.version+'\n\r发布日期:'+info.releaseDate+'\n\r文件大小:'+(parseInt(info.files[0].size)/1024/1024).toFixed(2)+'M',
				// 	buttons: ['立即更新','后台下载(下次登录自动更新)','不再提示'],
				// 	cancelId:3
				// }).then((index) => {
				// 	switch(index.response){
				// 		case 0:
				// 			//开始下载
				// 			electron.ipcRenderer.send("downloadUpdate",'0');
				// 			//进度
				// 			electron.ipcRenderer.removeAllListeners('downloadProgress');
				// 			electron.ipcRenderer.on("downloadProgress", (event, progressObj)=>{
				// 				$.HSAPI_LOADINGTIPS('文件:'+(parseInt(progressObj.total)/1024/1024).toFixed(2)+'M/'+(parseInt(progressObj.transferred)/1024/1024).toFixed(2)+'M;速度:'+(parseInt(progressObj.delta)/1024).toFixed(2)+'KB/S')
				// 			});
				// 			//执行更新
				// 			electron.ipcRenderer.removeAllListeners('isUpdateNow');
				// 			electron.ipcRenderer.on("isUpdateNow", () =>{
				// 				$.HSAPI_LOADINGTIPS('即将更新...')
				// 				setTimeout(function(){ 
				// 					$.HSAPI_LOADINGHIDE();
				// 					electron.ipcRenderer.send("isUpdateNow");
				// 				}, 3000);
				// 			});
				// 			$.HSAPI_LOADING({'loadingTips':'开始下载...'});
				// 			break
				// 		case 1:
				// 			alert('未完待续')
				// 			break;
				// 		case 2:
				// 			alert('未完待续')
				// 			break;
				// 		default:return;
				// 	}
				// });
			}
		});
	},
	//手动检查更新
	HSAPI_UPDATE:function(){
		let remote=electron.remote;
		let dialog=electron.remote.dialog;
		electron.ipcRenderer.send("checkForUpdate");
		electron.ipcRenderer.removeAllListeners('message');
		electron.ipcRenderer.on("message", (event, text,info) =>{
			let win=remote.getCurrentWindow(); 
			if(text=='-1'){
				dialog.showMessageBox(win, {
					type: 'error',
					title: '错误',
					message: '获取更新失败',
					buttons: ['知道了']
				}).then((index) => {
					return;
				});
			}
            if(text=='1'){
				dialog.showMessageBox(win, {
					type: 'info',
					title: '更新',
					message: '检测到新版本:'+info.version+'\n\r发布日期:'+info.releaseDate+'\n\r文件大小:'+(parseInt(info.files[0].size)/1024/1024).toFixed(2)+'M',
					buttons: ['立即更新','取消'],
					cancelId:3
				}).then((index) => {
					switch(index.response){
						case 0:
							$.HSAPI_UPDATEDOWNLOAD();
							break
						case 1:
							break;
						default:return;
					}
				});
			}
		});
	},
	//执行下载
	HSAPI_UPDATEDOWNLOAD:function(){
		try{
			//进度
			electron.ipcRenderer.removeAllListeners('downloadProgress');
			electron.ipcRenderer.on("downloadProgress", (event, progressObj)=>{
				$.HSAPI_LOADINGTIPS('文件:'+(parseInt(progressObj.total)/1024/1024).toFixed(2)+'M/'+(parseInt(progressObj.transferred)/1024/1024).toFixed(2)+'M;速度:'+(parseInt(progressObj.delta)/1024).toFixed(2)+'KB/S')
			});
			//执行更新
			electron.ipcRenderer.removeAllListeners('isUpdateNow');
			electron.ipcRenderer.on("isUpdateNow", () =>{
				$.HSAPI_LOADINGTIPS('即将更新...')
				setTimeout(function(){ 
					$.HSAPI_LOADINGHIDE();
					electron.ipcRenderer.send("isUpdateNow");
				}, 3000);
			});
			//提示
			$.HSAPI_LOADING({'loadingTips':'开始下载...'});
			//开始下载
			electron.ipcRenderer.send("downloadUpdate",'0');
		}catch(e){
			alert('更新失败:'+e)
			$.HSAPI_LOADINGHIDE();
		}
	},
	//等待
	HSAPI_LOADING:function(){
		var defaults = {
            opacity: 0.5,
            //loading页面透明度
            backgroundColor: "#000000",
            //loading页面背景色
            borderColor: "#bbb",
            //提示边框颜色
            borderWidth: 1,
            //提示边框宽度
            borderStyle: "solid",
            //提示边框样式
            loadingTips: "请稍等...",
            //提示文本
            TipsColor: "#666",
            //提示颜色
            delayTime: 1000,
            //页面加载完成后，加载页面渐出速度
            zindex: 1,
            //loading页面层次
            sleep: 0
            //设置挂起,等于0时则无需挂起
        }
        var options = $.extend(defaults, options);

        //获取页面宽高
        var _PageHeight = document.documentElement.clientHeight,
        _PageWidth = document.documentElement.clientWidth;

        //在页面未加载完毕之前显示的loading Html自定义内容
        var _LoadingHtml = '<div id="HSAPI_loadingPage" style="position:fixed;left:0;top:0;_position: absolute;width:100%;height:' + _PageHeight + 'px;background:' + options.backgroundColor + ';opacity:' + options.opacity + ';filter:alpha(opacity=' + options.opacity * 100 + ');"></div>';
            _LoadingHtml+='<div id="HSAPI_loadingTips" style="opacity:1;position: absolute; cursor1: wait; width: auto;border-color:' + options.borderColor + ';border-style:' + options.borderStyle + ';border-width:' + options.borderWidth + 'px; height:80px; line-height:80px; padding-left:80px; padding-right: 5px;border-radius:10px;  background: #fff url(../../images/loading.gif) no-repeat 5px center; color:' + options.TipsColor + ';font-size:20px;">' + options.loadingTips + '</div>';
        //呈现loading效果
        $("body").append(_LoadingHtml);

        //获取loading提示框宽高
        var _LoadingTipsH = document.getElementById("HSAPI_loadingTips").clientHeight,
        _LoadingTipsW = document.getElementById("HSAPI_loadingTips").clientWidth;

        //计算距离，让loading提示框保持在屏幕上下左右居中
        var _LoadingTop = _PageHeight > _LoadingTipsH ? (_PageHeight - _LoadingTipsH) / 2 : 0,
        _LoadingLeft = _PageWidth > _LoadingTipsW ? (_PageWidth - _LoadingTipsW) / 2 : 0;

        $("#HSAPI_loadingTips").css({
            "left": _LoadingLeft + "px",
            "top": _LoadingTop + "px"
        });
	},
	//等待文字变化
	HSAPI_LOADINGTIPS:function (value) {
		$("#HSAPI_loadingTips").html(value);
		//重新计算位置
		var _PageHeight = document.documentElement.clientHeight,
			_PageWidth = document.documentElement.clientWidth;
        var _LoadingTipsH = document.getElementById("HSAPI_loadingTips").clientHeight,
        	_LoadingTipsW = document.getElementById("HSAPI_loadingTips").clientWidth;
        var _LoadingTop = _PageHeight > _LoadingTipsH ? (_PageHeight - _LoadingTipsH) / 2 : 0,
        	_LoadingLeft = _PageWidth > _LoadingTipsW ? (_PageWidth - _LoadingTipsW) / 2 : 0;
        $("#HSAPI_loadingTips").css({
            "left": _LoadingLeft + "px",
            "top": _LoadingTop + "px"
        });
	},
	//取消等待
	HSAPI_LOADINGHIDE:function () {
		$("#HSAPI_loadingPage").remove();
		$("#HSAPI_loadingTips").remove();
	},
	//刷新
	HSAPI_REFRESHINDEX:function(){
		window.location.reload();
	},
	//关闭窗体
	HSAPI_CLOSEWINS:function(){
		electron.ipcRenderer.send("coloseWins");
	},
	//关闭主进程
	HSAPI_CLOSEEXE:function(){
		electron.ipcRenderer.send("closeMainExe");
	},
	//生成主进程菜单
	HSAPI_MAINMENU:function(menu_json,depsMenu_json){
		electron.ipcRenderer.send("creMainMenu",menu_json,depsMenu_json);
		electron.ipcRenderer.removeAllListeners('menuClick');
			electron.ipcRenderer.on("menuClick", (event, url)=>{
				// $('a[data-menucode="'+menuCode+'"]').trigger("click");
                import('../jquery.moudles.detail.js?'+Math.random()).then(data=>{
                    let moudles=data.moudles,moudlesFilter=[],urlHash=url;
                    Object.keys(moudles).forEach(key => {
                        if(urlHash.indexOf(key)>-1){
                            moudlesFilter=[...moudles[key]];
                        }
                    });
                    moudlesFilter.map((v,k)=>{
                        $.extend({
                            [v.moudle]:()=>{
                                return import(`${"."+v.path}`);
                            }
                        });
                    });
                }).then(()=>{
                    window.location.href = url
                });
                
			});

		electron.ipcRenderer.removeAllListeners('changeDep');
		electron.ipcRenderer.on("changeDep", (event, depCode)=>{
			jQuery.ajax( {  
				type : 'POST',  
				url : $.HSAPI_AJAXURL+"/qms/mobile/getToken",
				data : {
					dep:depCode
				},
				dataType : 'json',    
				async:false,
				success : function(data) {
					if(data.RETURN=='1'){
						$.HSAPI_HEADERS.token = data.token;
						localStorage.setItem('token', data.token);
						$.HSAPI_HEADERS.bmh=depCode;
						localStorage.setItem('bmh',depCode);
						window.location.reload();
					}
				},  
				error : function(data) {  
					jf_alert("修改session中的部门号失败"); 
				}  
			});
		});	
	},
	//直接登出到登录页面
	HSAPI_LOGOUT:function(){
		electron.ipcRenderer.send("coloseWinsToLogin");
	},
	//判断是否全屏
	HSAPI_ISFULLSCREEN:function(){
		return electron.remote.getCurrentWindow().isFullScreen();
	},
	//触屏版
	HSAPI_CLEARMENU:function(){
		electron.ipcRenderer.send("setApplicationMenu");
	},
	//构造窗体大小
	HSAPI_REBUILDSIZE:function(width,height){
		electron.remote.getCurrentWindow().setSize(width,height);
		electron.remote.getCurrentWindow().center();
	}
});

// 重写window.open
const _open=window.open;
window.open=function(url,target,params={}){
    if(target && target=="_self"){
        if(url.startsWith('#'))
            $.HSAPI_NEWWINDOW_SELF(params,url);
        else if(url.startsWith('/'))
            $.HSAPI_NEWWINDOW_SELF(params,'#'+url);
        else if(url.startsWith('html'))
            $.HSAPI_NEWWINDOW_SELF(params,'#/'+url);
        else{
            electron.ipcRenderer.send('downloadExcelFile',url);
        }
    }else{
        if(url.startsWith('#'))
            $.HSAPI_NEWWINDOW(params,url);
        else if(url.startsWith('/'))
            $.HSAPI_NEWWINDOW(params,'#'+url);
        else if(url.startsWith('html'))
            $.HSAPI_NEWWINDOW(params,'#/'+url);
        else{
            electron.ipcRenderer.send('downloadExcelFile',url);
        }
    }
	
}

//jquery扩展prototype方法
$.fn.extend({
	//获取表单JSON格式数据
	HSAPI_FORMJSONDATA:function(){
		var jsonArray=$(this).serializeArray();
		var i = 0,max = jsonArray.length,json={},e,name,lastarr;
		for (i=0; i < max; i++) {
			if ( jsonArray[i].value != null ){
				json[jsonArray[i].name] = jsonArray[i].value
			}
		};
		return json;
	},
	//推送
	HSAPI_WEBSOCKET:function(option){
		var defaultOpt={
			protocol:($.HSAPI_PROTOCOL()=="https:"?"wss://":"ws://"),
			url:"",
		}
		var opt=$.extend({},defaultOpt,option);

		if(!opt.hasOwnProperty("pageIdentify")){ 
			alert("缺少页面标识参数pageIdentify")
			return;
		}	
		if(typeof(WebSocket) == "undefined") {
			console.log("您的浏览器不支持WebSocket");
		}else{
			var {protocol,url}=opt;
			var socket = new WebSocket(protocol+$.HSAPI_LOCALHOSTPATH()+url+opt.pageIdentify);
			window.webSocketCtrl.push(socket);
			//打开事件   
            socket.onopen = function() {   
                console.log("Socket 已打开");  
                if($.isFunction(opt.send)) 
                	opt.send();
            };  
            //获得消息事件  
            socket.onmessage = function(msg) {
            	if($.isFunction(opt.onmessage)) 
            		opt.onmessage(msg); 
            };  
            //关闭事件  
            socket.onclose = function() {  
                console.log("Socket已关闭");
                if($.isFunction(opt.onclose))  
                	opt.onclose();
            };  
            //发生了错误事件  
            socket.onerror = function() { 
            	console.log("Socket发生错误");  
            	if($.isFunction(opt.onerror)) 
        			opt.onerror();
            }  
		}	
	}
}) 

/* ***************************************原B版公用函数*************************************** */
var pathName = document.location.pathname;
var index = pathName.substr(1).indexOf("/");
var path = pathName.substr(0, index + 1);
/**
 * 获取指定名称字典
 * @param arg 名称
 * @param dict 当前字典
 * @returns 当前字典json
 */
function sysgetdictBySource(arg,dict){

	var json = [];
	var data = dict;
	var max = data.length;

	var N = 0;
	for (i=0; i < max; i++) {
		if (data[i].grou_name==arg){
			json[N] = data[i];
			N ++;
		}
	};
	return json; 
}

/**
 * 获取指定名称字典
 * @param arg 名称
 * @returns 当前字典json
 */
function sysgetdict(arg){
	try{
		var json = [];
		var data;
		if(sessionStorage.getItem("hodict")!=null)
			data=JSON.parse(sessionStorage.getItem("hodict"));
		else{
			data=JSON.parse(localStorage.getItem("hodict"));	
		}
		 
		if(window.location.href.indexOf(path+"/group")>=0)
			data=JSON.parse(localStorage.getItem("Ghodict"));
			
		var max = data.length;
	
		var N = 0;
		for (i=0; i < max; i++) {
			if (data[i].grou_name==arg){
				json[N] = data[i];
				N ++;
			}
		};
		json = sortByKey(json, "c_sort");
		return json;
	}catch(e){  
		if(window.location.href.indexOf("/group/sys/sysuser/"))
			window.location.href=path+"/login/group/login.jsp";
	}
	
}

/**
 * 获取指定名称字典
 * @param arg 名称
 * @param dict 当前字典
 * @returns 当前带编码字典json
 */
//排序方法
function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((parseInt(x) < parseInt(y)) ? -1 : ((parseInt(x) > parseInt(y)) ? 1 : 0));
    });
}

function sysgetdictWithCodeBySource(arg,dict){

	var json = [{}];
	var data = dict;
	var max = data.length;

	var N = 0;
	for (i=0; i < max; i++) {
		if (data[i].grou_name==arg){
//			alert(data[i].descript1)
			var descript1=data[i].code+"-"+data[i].descript1;
			data[i].descript1=descript1;
			json[N] = data[i];
			N ++;
		}
	};
	
	return json;
	
}

/**
 * 获取指定名称字典
 * @param arg 名称
 * @returns 当前带编码字典json
 */
function sysgetdictWithCode(arg){

	var json = [{}];
	var data;
	if(sessionStorage.getItem("hodict")!=null)
		data=JSON.parse( sessionStorage.getItem("hodict") );
	else
		data=JSON.parse( localStorage.getItem("hodict") );
	var max = data.length;

	var N = 0;
	for (i=0; i < max; i++) {
		if (data[i].grou_name==arg){
//			alert(data[i].descript1)
			var descript1=data[i].code+"-"+data[i].descript1;
			data[i].descript1=descript1;
			json[N] = data[i];
			N ++;
		}
	};
	
	return json;
	
}

function getalinarg(arg){
	var json = [{}];
	var data;
	if(sessionStorage.getItem("alinarg")!=null)
		data=JSON.parse( sessionStorage.getItem("alinarg") );
	else
		data=JSON.parse( localStorage.getItem("alinarg") );
	var max = data.length;
	
	var N = 0;
	for (i=0; i < max; i++) {
		if ($.trim(data[i].id)==arg){
			json[N] = data[i];
			N ++;
		}
	};
	return json;
	
}


function sysjson2select( select,json,descript ){
	if(!select){return;}
	if(!descript){var descript=1}
	for (i=0; i < json.length; i++) {
		if(json[i].descript1){
			
			if(descript==2){
				select.options.add(new Option(json[i].descript2,json[i].code.replace(/(\s*$)/g, "")));
			}else{
				select.options.add(new Option(json[i].descript1,json[i].code.replace(/(\s*$)/g, "")));
			}
		}
	}
	
	
//	if ( i > 0 ){
//		options[0].defaultSelected = true;  
//		options[0].selected = true;
//	}
}


//信息脱敏
function desensitization(str, beginLen, endLen){
//    var len = str.length;
//    var firstStr = str.substr(0, beginLen);
//    var lastStr = str.substr(endLen);
//    var middleStr = str.substring(beginLen, len-Math.abs(endLen)).replace(/[\s\S]/ig, '*');
//
//    tempStr = firstStr+middleStr+lastStr;
//
//    return tempStr;
    
    if(typeof str == 'string'){ //参数为字符串类型
    	var ruten = str.substring(beginLen,endLen); //提取字符串下标之间的字符。
//    	var lastStr = str.substring(beginLen,endLen).replace(/[\s\S]/ig, '*');
        return str.replace(ruten,ruten.replace(/[\s\S]/ig, '*')); //字符串中用字符替换另外字符，或替换一个与正则表达式匹配的子串。
    }
}


//按照填name组的数据
function sysjson2name( form,json ){
		//填Free的信息
		var i = 0;
		var max = form.length;
		
		var e,name,lastarr;
		
		for (i=0; i < max; i++) {
			//e = form.elements[i];
			e = form[i];
			if ( e.name in json ){
				e.value = json[e.name];
			}
		};
	
}	

//form初始化
function sysformreset( form ){
		//填Free的信息
		var i = 0;
		var max = form.length;
		
		var e,name,lastarr;
		
		for (i=0; i < max; i++) {
			//e = form.elements[i];
			e = form[i];
			e.value = ''
		};
	
}	



//按照填name组的数据
function syssql2json( sqljson,parent_ID ){
		//填Free的信息
		var i = 0;
		var max = sqljson.length;
		var json={}
		
		var e,name,lastarr;
		
		for (i=0; i < max; i++) {
			
			if ( sqljson[i].StringValue != null && sqljson[i].parent_ID == parent_ID ){
				json[sqljson[i].NAME] = sqljson[i].StringValue
			}
		};
		return json
	
}	

//按照填name组的数据
function sysname2json( namejson ){
		//填Free的信息
		var i = 0;
		var max = namejson.length;
		var json={}

		var e,name,lastarr;
		
		for (i=0; i < max; i++) {
			
			if ( namejson[i].value != null ){
				json[namejson[i].name] = namejson[i].value
			}
		};
		return json
	
}	

//获得URL参数
function sysGetQueryString(name)
{    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = decodeURIComponent(window.location.href).substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}


//提取后台返回值 MSG
function sysajaxsuccessMSG( data ){
	var msg = ''	
	var danger=''
	var warn = '' 
	var info = '' 
		
	
	if ('MSG' in data){
		msg  = data.MSG	
	}else{
		msg  = JSON.stringify(data)	
	}
	if ('DANGER' in data){
		if (data.DANGER.length != 0 ){
			danger = '<span class="label label-danger arrowed-in">'+$.i18n.propJsp("风险提示")+':</span><br><span class="red">' + data.DANGER + '</span>'
		}
	}

	if ('WARNMSG' in data){
		if (data.WARNMSG.length != 0 ){
			warn = '<span class="label label-warning">'+$.i18n.propJsp("警告")+':</span><br><span class="orange">' + data.WARNMSG + '</span>'
		}
	}
	
	if ('INFOMSG' in data){
		if (data.INFOMSG.length != 0 ){
			info = '<span class="label label-info">'+$.i18n.propJsp("提示")+':</span><br>' + data.INFOMSG
		}
	}

	return msg + '<br>' + danger + warn + info
}	


function systoast( title,text,type,left,light ){
	if(!title){title=$.i18n.propJsp("提示")+':'}
	if(!text){text=''}
	class_name= ((left)?'' : 'gritter-center')
	
	if (type){
		switch (type) {
		  case 'error': 
			  class_name= 'gritter-error ' + ((left)?'' : 'gritter-center') + ((light=='light')?' gritter-light' : '') ;
			  break;
		  case 'warning': 
			  class_name= 'gritter-warning ' + ((left)?'' : 'gritter-center') + ((light=='light')?' gritter-light' : '');
			  break;
		  case 'info': 
		  	  class_name= 'gritter-info ' + ((left)?'' : 'gritter-center') + ((light=='light')?' gritter-light' : '');
		    break;
		  case 'success': 
		  	  class_name= 'gritter-success ' + ((left)?'' : 'gritter-center') + ((light=='light')?' gritter-light' : '');
		    break;
		  
		}
	}
	$.gritter.add({
		title: $.i18n.propJsp(title),
		text: $.i18n.propJsp(text),
		class_name: class_name
	});
	
	
}


//按照填class为fill的数据
function sysjson2fill( form,data){
		//填Free的信息
		var i = 0;
		var max = form.length;
		
		var e,name,lastarr;
		// 循环处理class为fill的元素
		if (data){
			var json =  data
			for (i=0; i < max; i++) {
				//e = form.elements[i];
				e = form[i];
				e.innerHTML = '';
				e.value='';
				if (json[e.id]){
					e.innerHTML = json[e.id];
					e.value=json[e.id];
				}
			};
		}else{
			for (i=0; i < max; i++) {
				//e = form.elements[i];
				e = form[i];
				e.innerHTML = '';
				e.value=''
			};
		};
	
}

/*
*替换当前url
*2016-12-05
*/
function replaceUrl(url){
	var json={time:new Date().getTime()};
	window.history.replaceState(json,"",url);
}

//获取照片路径
function getRootPath(){
    var curWwwPath=window.document.location.href;
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    var localhostPaht=curWwwPath.substring(0,pos);
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName+"/static/hotel/image/");
}

//提示框
function jf_alert(MSG,fn){
	
	var showdivs='<h3 class="header smaller lighter red">'
	showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
	showdivs=showdivs+  $.i18n.propJsp(MSG)
	showdivs=showdivs+'</h3>'
		
	bootbox.dialog({
		message: showdivs,
		onEscape:true,
		buttons: 			
		{
			"button" :{
				"label" : $.i18n.propJsp("确定"),
				"className" : "btn-info",
				"callback": fn?fn:function(){}
			},Cancel: {
				label: "取消",
				className: "btn-default",
				callback: function () {
					
				}
			}
		}
	});
}

function jf_successDelayed(MSG,time,gritterParams){ 
	var style="",posi="gritter-center-hs",color="yellow";
	if(!time)
		time=2000;
	if(gritterParams){
		if(gritterParams.hasOwnProperty("color"))
			color=gritterParams.color;
		if(gritterParams.hasOwnProperty("bgcolor"))
			style=style+"background:"+gritterParams.bgcolor+";";  
		if(gritterParams.hasOwnProperty("tcolor"))
			style=style+"color:"+gritterParams.tcolor+";"; 
		if(gritterParams.hasOwnProperty("position")){
			var position=gritterParams.position;
			if(position!="center")
				posi="";
		}
	}  
	var title="";
	if($.hasOwnProperty("i18n")&&$.i18n.hasOwnProperty("propJsp")) 
		title=$.i18n.propJsp("提示"); 
	else
		title="提示";
		
	$.gritter.add({
		title: '<font color="'+color+'">'+title+'</font>',  
		text:$.i18n.propJsp(MSG), 
		time: time,
		speed:500,
		class_name: ' gritter-item-wrapper '+posi,   
		style:style
	});
}

function jf_alert_jqgriderror(MSG,fn){
	var showdivs='<h3 class="header smaller lighter red">'
		showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
		var arr = MSG.split("<br>")
		showdivs=showdivs+ arr[0] + arr[1]+ '</h5>' +  
					'<code style="word-break: break-all;word-wrap: break-word;" width:559px;font-size:15px;>'+   
						
					'</code>'+
					'<h5 style="word-wrap:break-word">' + arr[3]
		showdivs=showdivs+'</h3>'
		bootbox.dialog({
			message: showdivs,
			onEscape:true,
			buttons: 			
			{
				"button" :
				{
					"label" : $.i18n.propJsp("确定"),
					"className" : "btn-sm",
					"callback": fn?fn:function(){ 
			        	
			        }
				},
			}
		});
	
		setTimeout(function(){
			$(document).find("code").html(arr[2])
		},20)
}

//提示框
function jf_success(MSG,fn){
	
	var showdivs='<h3 class="header smaller lighter green">'
	showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
	showdivs=showdivs+MSG
	showdivs=showdivs+'</h3>'
		
	bootbox.dialog({
		message: showdivs,
		buttons: 			
		{
			"button" :
			{
				"label" : $.i18n.propJsp("确定"),
				"className" : "btn-sm",
				"callback": fn?fn:function(){
		        	
		        },
			}
		},
	 onEscape: true,  
	});
}

//确认框
function jf_confirm(MSG,res){
	
	var showdivs='<h3 class="header smaller lighter blue">'
	showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
	showdivs=showdivs+$.i18n.propJsp(MSG)
	showdivs=showdivs+'</h3>'
	
	bootbox.confirm({  
        buttons: {  
            confirm: {  
                label: $.i18n.propJsp("确认"),  
                className: 'btn-sm btn-primary'  
            },  
            cancel: {  
                label: $.i18n.propJsp("取消"),  
                className: 'btn-sm'  
            }  
        },  
        message: showdivs,  
        callback: function(result) {  
        	res(result);
        },  
          
    });
}

//确认框
function jf_confirm_yn(MSG,res){
	
	var showdivs='<h3 class="header smaller lighter blue">'
	showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
	showdivs=showdivs+MSG
	showdivs=showdivs+'</h3>'
	
	bootbox.confirm({  
        buttons: {
        	cancel: {  
                label: $.i18n.propJsp("否"),  
              className: 'btn-sm'  
            },
            confirm: {  
                label: $.i18n.propJsp("是"),  
                className: 'btn-sm btn-primary'  
            },  
                
        },  
        message: showdivs,  
        callback: function(result) {  
        	res(result);
        },  
    });
}

//确认框
function jf_confirm_ync(MSG,res){
	
	var showdivs='<h3 class="header smaller lighter blue">'
	showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
	showdivs=showdivs+MSG
	showdivs=showdivs+'</h3>'
	
	bootbox.dialog({
		message: showdivs,
		buttons: 			
		{
			"info" :
			{
				"label" : $.i18n.propJsp("是"), 
				"className" : "btn btn-app btn-info",
				"callback": function() {
					res("是")
				}
			},
			"button" :
			{
				"label" : $.i18n.propJsp("否"),
				"className" : "btn btn-app btn-danger",
				"callback": function() {
					res("否")
				}
			},
			"danger" :
			{
				"label" : $.i18n.propJsp("取消"),
				"className" : "btn btn-app ",
				"callback": function() {
					res("取消")
				}
			}
		}
	});
}

//确认框
function jf_confirm_ynbig(MSG,res){
	
	var showdivs='<h3 class="header smaller lighter blue">'
	showdivs=showdivs+'<i class="ace-icon fa fa-bullhorn"></i>'
	showdivs=showdivs+MSG
	showdivs=showdivs+'</h3>'
	
	bootbox.dialog({
		message: showdivs,
		buttons: 			
		{
			"info" :
			{
				"label" : $.i18n.propJsp("是"), 
				"className" : "btn btn-app btn-info",
				"callback": function() {
					res("是")
				}
			},
			"button" :
			{
				"label" : $.i18n.propJsp("否"),
				"className" : "btn btn-app btn-danger",
				"callback": function() {
					res("否")
				}
			},
		}
	});
}

//消息提示框(提示)
function jf_alert_gritter_info(title,text){
	$.gritter.add({
		title: title,
		text: text,
		time: 2000,
		class_name: 'gritter-info gritter-center'
	});
}

//消息提示框(错误)
function jf_alert_gritter_error(title,text){
	$.gritter.add({
		title: title,
		text: text,
		time: 2000,
		class_name: 'gritter-error gritter-center'
	});
}

//消息提示框(成功)
function jf_alert_gritter_success(title,text){
	$.gritter.add({
		title: title,
		text: text,
		time: 2000,
		class_name: 'gritter-success gritter-center'
	});
}
/**
 * 获取酒店编号
 * @returns 酒店编号
 */  
function jf_getHotelId(){
	//集团加载单店页面
	var pathnameGroup=window.location.pathname;
	if(pathnameGroup.indexOf(path+"/group/")>=0) 
		return null;
	//集团跳转单店页面
	if(sessionStorage.getItem("hotelId")!=null){//集团
		var hotelId=sessionStorage.getItem("hotelId");
		return hotelId
	}else{//单店
		var hotelId=localStorage.getItem('hotelId');
		return hotelId;
	}
}

/**
 * 集团跳转
 */
function jf_open(hotelid,url){
	sessionStorage.setItem("hotelId",hotelid); 
	jQuery.ajax({  
		type : 'get',
		url : path+"/frontoffice/sys/sysuser/home",  
		sync:false,
		headers:{
			hotelId:sessionStorage.getItem("hotelId"),
			group:1,
		},  
		error : function(data){  
			systoast($.i18n.propJsp("提示")+':',$.i18n.propJsp("跳转目标酒店失败")+ JSON.stringify(data),'error');
		}  
	}); 
	window.open(path+"/frontoffice/sys/sysuser/home#page"+url+"&returnOrClose=close","_blank");
}

/**
 * 获取指定名称jqgrid字典
 * @param jsp 页面名称
 * @param jqgrid 表格id
 * @returns 当前字典json
 */
function getJqgridDict(jsp,jqgrid){
	var JqgridDict=localStorage.getItem("jqgridDict");
	var returnValue="";
	$(JSON.parse(JqgridDict)).each(function(key,value){ 
		if(value.jsp==jsp&&value.jqgrid==jqgrid)
			returnValue=value.sortby;
	})
	return returnValue;
}

//对Date的扩展，将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
//例子：
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
//(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, // 月份
		"d+": this.getDate(), // 日
		"h+": this.getHours(), // 小时
		"m+": this.getMinutes(), // 分
		"s+": this.getSeconds(), // 秒
		"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
		"S": this.getMilliseconds() // 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

//补全数据长度
function fillNumber(num){
	num=num.toString()
	if(num.length==1||num.length==0){
		return "0"+num
	}else if(num.length==2){
		return num
	}
}

//加载服务器自定义资源文件
  function importCustomizeJs(file,err,callBack){
	var pathName = window.location.pathname.substring(1); 
	var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));  
	var urlpath= window.location.protocol + '//' + window.location.host + '/'+ webName;  
	var path=urlpath.substring(0,urlpath.lastIndexOf("/"));
//	$.ajax(path+'/js/'+jf_getHotelId()+'/'+file, {
//        type: 'get',
//        sync:false,
//        timeout: 1000,
//        success: function() {
        	var x = 9999999; 
            var y = 0;
            var rand = parseInt(Math.random() * (x - y + 1) + y); 
            $.getScript(path+'/js/'+jf_getHotelId()+'/'+file+"?v="+rand)
			 .done(function() {
				 callBack(true);  
			 }).fail(function(){
//				 jf_alert(err);  
				callBack(false);    
			 });
//        	$(".page-content-area").ace_ajax("loadScripts", [path+'/js/'+jf_getHotelId()+'/'+file+"?v="+rand],function(){
//        		callBack(true); 
//        	}); 
//        }, 
//        error: function() { 
//        	jf_alert(err); 
//        	callBack(false); 
//        }
//    });
  }
  
  /**
   * 获取餐饮字典
   * fu:存储过程callname
   * param:自定义参数
   */
  function jf_getPosDict(fu,bh,url){  
    if(typeof(url)=="undefined")
	  url=$.HSAPI_PROCEDURE2_LIST;
	if(fu){   
		var hotelId=localStorage.getItem("hotelId")||"";  
		if(hotelId==""){
			jf_alert_gritter_error("错误",'获取餐饮字典错误无hotelID');
			return;
		}
		
		//默认参数
		var fuArray={
			"POSMenuSearch":{},
			"POSMenuSearchBycb":{"where":{"bh":bh}},
			"POSMenuSearchBycbdl":{"where":{"bh":bh}},
			"POSArgDictDefaultBybmh":{"arg":{"arg":"*"}}, 
			"POSArgBaseDefaultBybmh":{"arg":{}}, 
		}
		
		var storageArray=["menu","menucb","menudl","hodict_bybmh","BaseDefaultBybmh"];//key为BaseDefaultBybmh的要单独处理，返回的结果要以返回的key做为名称存在内存中
		
		if(fu=="all"){
			var i=0;
			for(item in fuArray){
				var fu=item;
				var param=fuArray[item];
				var mode="";
				if(i==0||i==3) 
					mode="list"
				getPosData(param,fu,hotelId,storageArray[i],mode,url);
				i++;
			}
			var date = new Date();
			var dateStr = date.toLocaleString();
			localStorage.setItem("menuLoadTime",dateStr)
		}else{
			var i=0;
			for(item in fuArray){
				if(fu==item){
					var fu=item;
					var param=fuArray[item]; 
					var mode="";
					if(i==0||i==3)
						mode="list"
					getPosData(param,fu,hotelId,storageArray[i],mode,url);
				};
				i++;
			}
			if(fu="POSMenuSearch"){
				var date = new Date();
				var dateStr = date.toLocaleString();
				localStorage.setItem("menuLoadTime",dateStr)
			}
		}
  	}else{
		jf_alert_gritter_error("错误",$.i18n.propJsp("参数错误")+":<br>"+$.i18n.propJsp("调用格式")+"->jf_getPosDict('"+$.i18n.propJsp("存储过程名称")+"(fu)','"+$.i18n.propJsp("参数")+"(param)')<br>" + 
		$.i18n.propJsp("参数格式")+":fu"+$.i18n.propJsp("传")+"callname/all->{BH}<br>");
  	}
  }
  
  function getPosData(param,fu,hotelId,key,mode,url){///qms/mobile/procedure2	$.HSAPI_CALLPROC2(param,fu)
	  jQuery.ajax({  
	  		type : 'POST',
	  		url : $.HSAPI_AJAXURL+url,  
	  		sync:false,
			headers : $.HSAPI_HEADERS,
	  		data : $.HSAPI_ASKJSONINFO(JSON.stringify(param),fu,"{}",mode), 
	        dataType : 'json',  
	        success : function(data) {
	        	if(Array.isArray(data)){
	        		localStorage.setItem(key,JSON.stringify(data));
	        	}else{
	        		if(data&&data.RETURN=="1"){
	        			for(var item in data){ 
	        				if(typeof(data[item])=="object"){
	        					if(key=="BaseDefaultBybmh"){
	        						localStorage.setItem(item,JSON.stringify(data[item]));  
	        					}else{
	        						localStorage.setItem(key,JSON.stringify(data[item]));  
	        					}
	        				}
	        			}
					}else if(data&&data[0]) 
						jf_alert_gritter_error("错误",data[0].MSG);
	        	}
	        },
	  		error : function(data){  
				jf_alert_gritter_error("交互错误",JSON.stringify(data));
	  		}  
	  	});
  }
  
  //存入日志
  function log(msg,logtype,keyword,tablename){
	  jQuery.ajax({  
			type : 'post',
			url : path+"/frontoffice/front/hoguest/log",  
			sync:false,
			data:{
				msg:msg,
				logtype:logtype,
				keyword:keyword,
				tablename:tablename
			},
			headers:{
				hotelId:jf_getHotelId(), 
			},  
			error : function(data){  
				systoast($.i18n.propJsp("提示")+':',$.i18n.propJsp("存入日志失败") + JSON.stringify(data),'error');
			}  
		});
  }
  
  //计算时间差
  function getTimeRange(date,currentDate){
//	  var currentDate = new Date();//当前时间
	  var startDate = new Date(date); //结束时间
	  var bad =  currentDate.getTime() - startDate.getTime();//时间差好秒数
	   
	  var badDay = Math.floor(bad/(24*3600*1000));//差值天
	   
	  var hMs = bad%(24*3600*1000)          //计算天数后剩余的毫秒数
	  var badHours = Math.floor(hMs/(3600*1000)); //差值小时
	   
	   
	  //计算相差分钟数
	  var mMs = hMs%(3600*1000);            //计算小时数后剩余的毫秒数
	  var badMinutes = Math.floor(mMs/(60*1000));//差值分钟
	    
	   
	  //计算相差秒数
	  var ms = mMs%(60*1000);             //计算分钟数后剩余的毫秒数
	  var badSeconds = Math.round(ms/1000);//差值秒
	  
	  return badHours+$.i18n.propJsp("时")+badMinutes+$.i18n.propJsp("分")
  }
  
	function getWeekValue(date){
//		date= Date.parse(date.substring(0,4)+"-"+date.substring(5,7)+"-"+date.substring(8,10));
		date= date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6,8);
		var week=new Date(date).getDay();//获取星期几
		var weekday=""
		if(week=="0"){
			weekday=$.i18n.propJsp("日");
		}
		else if(week=="1"){
			weekday=$.i18n.propJsp("一");
		}
		else if(week=="2"){
			weekday=$.i18n.propJsp("二");
		}
		else if(week=="3"){
			weekday=$.i18n.propJsp("三");
		}
		else if(week=="4"){
			weekday=$.i18n.propJsp("四");
		}
		else if(week=="5"){
			weekday=$.i18n.propJsp("五");
		}
		else if(week=="6"){
			weekday=$.i18n.propJsp("六");
		}
		return weekday
	}
	
	function getGap(startd,endd){
		var gap=parseInt( (endd - startd)  / Number(1000)/ Number(60) / Number(60) /Number(24) )
		return gap
	}

    function getSqlText(searchFormId,selectname){
        var sqlwhere = {"where":{},arg:{"selectname":selectname},radio:{},checkbox:{}}
        
        var all_search = $("#all_search").val()
    // 			var searchName = $("#searchName").val()
    // 			if(all_search&&searchName){
    // 				sqlwhere.where[searchName] = all_search
    // 			}else{
            sqlwhere.where.all_search = all_search
    // 			}
        
        if($("input[name='fuzzy']:checked").val()=="yes"){
            sqlwhere.arg['fuzzy'] = 'yes'
        }else{
            sqlwhere.arg['fuzzy'] = 'no'
        }
        
        var js = sysname2json($(searchFormId).serializeArray());
        sqlwhere.where = js
        
        $(searchFormId).find("select[class='multiselect']").each(function(){
            var $this = $(this)
            var selectId = $(this).attr("id")
            var valueArr = []
            $($this).parent("div").find(".multiselect-container li").each(function(){
                if($(this).hasClass("active")){
                    valueArr.push($(this).find("input").attr("value"))
                }
            })
            sqlwhere.where[selectId] = valueArr.join(",")
        })
        
        $(searchFormId).find("input[type='checkbox']:checked").each(function(){
            sqlwhere.checkbox[$(this).attr("name")] = 'yes'
            delete sqlwhere.where[$(this).attr("name")]
        })
        delete sqlwhere.checkbox['fuzzy']
        
        $(searchFormId).find("input[type='radio']:checked").each(function(){
            sqlwhere.radio[$(this).attr("name")] = $(this).attr("value")
            delete sqlwhere.where[$(this).attr("name")]
        })
        
        ins_argjson.sqlwhere = sqlwhere
        return sqlwhere;
    }
    
	
	//jqgrid 附加列
	function jqgrid_col_add(colNames,colModel,addition){
		var outJson = {"colNames":colNames,"colModel":colModel,"sort":""}
		$.each(addition,function(key,value){
//			debugger
			if(value.ifsort=="1"){
				outJson.sort = value.modle
			}
			var position = colNames.indexOf(value.foremodle)+1
			var newcolModel = {
					name : value.modle,//"sort",
					index : value.modle,
					width : value.width,
					align : (value.style!=""?value.style:((value.valuetype=="numeric")?"right":"left")),
					hidden:(value.ifhide=="1")?true:false,
					key:(value.ifkey=="1")?true:false,
					classes:(value.valuetype=="numeric")?"need_statistics":"",
					formatter : function(cellvalue,options,rowObject){
//						console.log(cellvalue)
//						console.log(options)
//						console.log(rowObject)
						var str = cellvalue
						// debugger
						if(value.formatter!=""){
							// eval(value.formatter);
                            var html = reconvert(value.formatter)
                            eval(html);
							// if(typeof(cellvalue)=="undefined" || cellvalue=="undefined"){
                            //     var html = reconvert(value.formatter)
                            //     eval(html);
							// }
							var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
							
							str = str.toString().replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
 						}
						
						return str
					},	
				}
			
			colNames.splice(position, 0, value.name);
			colModel.splice(position, 0, newcolModel);
		})
		
		return outJson
	}

    function reconvert(str){ 
            str = str.replace(/(\\u)(\w{1,4})/gi,function($0){ 
                return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g,"$2")),16))); 
            }); 
            str = str.replace(/(&#x)(\w{1,4});/gi,function($0){ 
                return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g,"$2"),16)); 
            }); 
            str = str.replace(/(&#)(\d{1,6});/gi,function($0){ 
                return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g,"$2"))); 
            }); 
             
            return str; 
    }
	
	//显示自定义tip
	function showTip(){
		var ctime;
		$(".custom_tip").each(function() {
			var title = $(this).attr('data-tip'); 
			if (title == undefined || title == "") return; 
			var a = $(this); 	
 			$(this).parent("td").removeAttr("title")
 			
     		$(this).data('title', title).hover(function (e){
     			clearTimeout(ctime); 
     			$("#anchortitlecontainer").remove(); 
	        		var offset = a.offset(); 
	        		var left = offset.left ;
	        		var top = offset.top + a.outerHeight() + 5;
	        		$("<div id=\"anchortitlecontainer\" style='position: absolute;z-index: 5999;border: solid 1px #315B6C;padding: 5px;color: #315B6C;background: none repeat scroll 0 0 #FFFFFF;border-radius: 5px;display: none;word-wrap: break-word !important;word-break: normal;max-width:400px;'></div>").appendTo($("body")).html(title).css({ top: top, left: left }).fadeIn(function () { 
		        		var pop = $(this); 
//		        		setTimeout(function () { pop.remove(); },4000); 
	        		}); 
	        		
	        		var csstext = ""
	        		if(left+400>=($(window).width()-80)){//宽度超出屏幕
//	        			csstext = 	'<style>'+
//						        		'#anchortitlecontainer:before {position: absolute;bottom: auto;right: -1px;top: -15px;border-color: transparent #315B6C transparent transparent;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//						        		'#anchortitlecontainer:after {position: absolute;bottom: auto;right: 0px;top: -13px;border-color: transparent #FFFFFF transparent transparent;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//									'</style>';
//	        			$('#anchortitlecontainer').prepend(csstext)
	        			
	        			if(top+$('#anchortitlecontainer').height()>=$(window).height()){//高度超出屏幕
//	        				csstext = 	'<style>'+
//							        		'#anchortitlecontainer:before {position: absolute;bottom: auto;right: -1px;bottom: -15px;border-color: transparent #315B6C transparent transparent;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//							        		'#anchortitlecontainer:after {position: absolute;bottom: auto;right: 0px;bottom: -13px;border-color: transparent #FFFFFF transparent transparent;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//										'</style>';
//							$('#anchortitlecontainer').find("style").remove();
//							$('#anchortitlecontainer').prepend(csstext);
	        				var left = offset.left+ a.outerWidth()/2 - $('#anchortitlecontainer').width();
		        			if(left + $('#anchortitlecontainer').width()>=($(window).width()-80)){
		        				left = $(window).width()-80-$('#anchortitlecontainer').width()
		        			}
		        			top = offset.top - $('#anchortitlecontainer').height() -5 -15 
		        			$('#anchortitlecontainer').css({ top: top,left: left })
	        			}else{//高度没有超出屏幕
	        				var left = offset.left+ a.outerWidth()/2 - $('#anchortitlecontainer').width();
		        			if(left + $('#anchortitlecontainer').width()>=($(window).width()-80)){
		        				left = $(window).width()-80-$('#anchortitlecontainer').width()
		        			}
		        			$('#anchortitlecontainer').css({ left: left })
	        			}
	        			
	        			
	        		}else{//宽度没有超出屏幕
	        			
	        			if(top+$('#anchortitlecontainer').height()>=$(window).height()){//高度超出屏幕
//	        				csstext = 	'<style>'+
//							        		'#anchortitlecontainer:before {position: absolute;bottom: auto;left: -1px;bottom: -15px;border-color: transparent transparent transparent #315B6C;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//							        		'#anchortitlecontainer:after {position: absolute;bottom: auto;left: 0px;bottom: -13px;border-color: transparent transparent transparent #FFFFFF;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//										'</style>';
//							$('#anchortitlecontainer').prepend(csstext)
		        			top = offset.top - $('#anchortitlecontainer').height() -5 -15 
		        			$('#anchortitlecontainer').css({ top: top })
	        			}else{//高度没有超出屏幕
//	        				csstext = 	'<style>'+
//							        		'#anchortitlecontainer:before {position: absolute;bottom: auto;left: -1px;top: -15px;border-color: transparent transparent transparent #315B6C;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//							        		'#anchortitlecontainer:after {position: absolute;bottom: auto;left: 0px;top: -13px;border-color: transparent transparent transparent #FFFFFF;border-style: solid;border-width: 15px;content: "";display: block;width: 0;}'+
//										'</style>';
//							$('#anchortitlecontainer').prepend(csstext)
	        			}
	        			
	        			
	        		}
	        		
	        		$("#anchortitlecontainer").hover(function (){
	        			clearTimeout(ctime);
	         		},function(){
	         			$("#anchortitlecontainer").remove(); 
	         		})
	        		
     		},function(e) {
     			ctime = setTimeout(() => {
					if(e.target.id!="anchortitlecontainer" ){
						$("#anchortitlecontainer").remove(); 
						clearTimeout(ctime);
					}
				}, 500);
//      			$("#anchortitlecontainer").remove(); 
     		}); 
     		
 		}); 
		
		
	}
	
	//通用图标字体样式（json格式数据，附加css，标签ID）
	function getTextStyle(value,extendCss,id){
		var text = ""
		var csstype = (value["csstype"]?value["csstype"]:"text")
		var tcolor = (value["tcolor"]?value["tcolor"]:"")
		var bgcolor = (value["bgcolor"]?value["bgcolor"]:"rgba(0,0,0,0)")
		var bgcolor_text = (bgcolor!="rgba(0,0,0,0)"?bgcolor.replace(/#/g, "a"):"a0000")
		var height = (value["height"]?(value["height"]+"px"):"")
		
		
		var right_in = (value["height"]?("-"+Number(value["height"])/4+"px"):"-5px")
		var right_out = (value["height"]?("-"+Number(value["height"])/2+"px"):"-10px")
		var borderWidth = (value["height"]?(Number(value["height"])/2+"px "+Number(value["height"])/4+"px"):"10px 5px")
		
		extendCss = (value["csstext"]?";"+value["csstext"]+";"+extendCss+";":extendCss)
		
		
		var css = 'color:'+tcolor+' !important;background-color:'+bgcolor+' !important;height:'+height+' !important;'
		var text = (value["name"]?value["name"]:"")
		
		var style_id = ""
		if(!id){
			id=""
			style_id=""
		}else{
			id=id
			style_id="#"+id
		}
		
		if(text!="" && JSON.stringify(value)!="{}"){
			switch (csstype) {
			case "text":
				text = '<span id="'+id+'" class="" style="'+css+''+extendCss+'">'+text+'</span>';
				break;
			case "circle":
				if(bgcolor=="rgba(0,0,0,0)"){
					css = 'color:'+tcolor+' !important;background-color:'+bgcolor+' !important;height:'+height+' !important;border:1px solid '+tcolor+';'
				}
				text = '<span id="'+id+'" class="badge" style="'+css+''+extendCss+'">'+text+'</span>';
				break;
			case "arrowed":
				var radius = (value["radius"]?(value["radius"]+"px"):'0px')
				if(bgcolor=="rgba(0,0,0,0)"){
					css = 'color:'+tcolor+' !important;background-color:'+bgcolor+' !important;height:'+height+' !important;border:1px solid '+tcolor+';border-radius:'+radius+';'
				}
				
				text = '<span id="'+id+'" class="label '+bgcolor_text+'" style="'+css+''+extendCss+'">'+text+'</span>'
				break;
			case "arrowed-inin":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed-in-right arrowed-in" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed-in:before{left:'+right_in+';border-width:'+borderWidth+';border-color:'+bgcolor+' !important;border-left-color: transparent !important;}'+
									style_id+'.label.'+bgcolor_text+'.arrowed-in-right:after{right:'+right_in+';border-width:'+borderWidth+';border-color:'+bgcolor+' !important;border-right-color: transparent !important;}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-outout":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed arrowed-right" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed:before{left:'+right_out+';border-width:'+borderWidth+';border-right-color:'+bgcolor+' !important}'+
									style_id+'.label.'+bgcolor_text+'.arrowed-right:after{right:'+right_out+';border-width:'+borderWidth+';border-left-color:'+bgcolor+' !important}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-inout":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed-in arrowed-right" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed-in:before{left:'+right_in+';border-width:'+borderWidth+';border-color:'+bgcolor+' !important;border-left-color: transparent !important;}'+
									style_id+'.label.'+bgcolor_text+'.arrowed-right:after{right:'+right_out+';border-width:'+borderWidth+';border-left-color:'+bgcolor+' !important}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-outin":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed arrowed-in-right" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed:before{left:'+right_out+';border-width:'+borderWidth+';border-right-color:'+bgcolor+' !important}'+
									style_id+'.label.'+bgcolor_text+'.arrowed-in-right:after{right:'+right_in+';border-width:'+borderWidth+';border-color:'+bgcolor+' !important;border-right-color: transparent !important;}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-midin":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed-in-right" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed-in-right:after{right:'+right_in+';border-width:'+borderWidth+';border-color:'+bgcolor+' !important;border-right-color: transparent !important;}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-midout":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed-right" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed-right:after{right:'+right_out+';border-width:'+borderWidth+';border-left-color:'+bgcolor+' !important}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-inmid":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed-in" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed-in:before{left:'+right_in+';border-width:'+borderWidth+';border-color:'+bgcolor+' !important;border-left-color: transparent !important;}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "arrowed-outmid":
				text = '<span id="'+id+'" class="label '+bgcolor_text+' arrowed" style="'+css+''+extendCss+'">'+text+'</span>'
				var csstext = 	'<style>'+
									style_id+'.label.'+bgcolor_text+'.arrowed:before{left:'+right_out+';border-width:'+borderWidth+';border-right-color:'+bgcolor+' !important;}'+
								'</style>';
				$(csstext).appendTo('.row')
				break;
			case "icon":
				text = '<i id="'+id+'" class="ace-icon fa '+text+'" style="color:'+tcolor+' !important;margin-right:2px;'+extendCss+'"></i>'
				break;
			default:
				text = '<span id="'+id+'" class="" style="'+css+''+extendCss+'">'+text+'</span>';
				break;
			}
			text = text+"&nbsp;"
		}
		
		return text
	}
	
	var loadingTimer;
	function showLoading(back){
		clearInterval(loadingTimer);
		$("#LoadingModal,#LoadingIcon").remove();
		
		var number = 0
		var html = 	'<div id="LoadingModal" class="" style="position:fixed;top:0;left:0;width: 100%; height:100%; background:#393939; filter:alpha(opacity=70); z-index:10600;opacity:0.2; "></div>'+
					'<div id="LoadingIcon" class="loading" style="position: fixed;left: 50%;top: 50%;width: 100%;height: 100%;z-index: 19890;">'+				
						'<i class="ace-icon fa fa-spinner fa-spin orange" style="zoom: 340%;"></i>'+
						'<span id="LoadingNum" style="position: absolute;left: 17px;top: 8px;font-size: 18px;color: #fd8c32;font-weight: bold;"></span>'+
					'</div>';
		$("body").append(html)
		
		loadingTimer = window.setInterval(() => {
			number = number+1;
			if(number>=3){
				$("#LoadingNum").text(number)
				if(number>=10 && number<=99){
					$("#LoadingNum").css("left","13px").css("top","9px").css("font-size","15px")
				}
				if(number>=100 && number<=999){
					$("#LoadingNum").css("left","11px").css("top","13px").css("font-size","12px")
				}
			}
		}, 1000);
		
		if(back){
			back();
		}
	}
	
	function hideLoading(back){
		clearInterval(loadingTimer);
		$("#LoadingModal,#LoadingIcon").remove();
		
		if(back){
			back();
		}
	}

	function aTagOpenWindow(el){
		var url = $(el).data("url");
		window.open(url);
	}

    function getPath(){
        electron.ipcRenderer.send("getApp",function(data){
            debugger
            return data
        });
    }

    function customHtmlBuild(data,scrname){

        var statement = `
<!DOCTYPE html>
`
var a = `
    <html lang="cn">
        <head>
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
            <meta charset="utf-8" />
            <title>PMS-business</title>
            <meta name="description" content="overview &amp; stats" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
        </head>
        <style>
            input{
                border: 1px solid #D5D5D5;
            }
        </style>
        <body>
            <div class="row" id="customBox" style="margin-bottom: -24px;position: relative;">
 `
                    var z = `
        </div>
        <script type="text/javascript"> 
            var ins_argjson={};
            ins_argjson.scrname = '`+scrname+`'
            $(".page-content-area").ace_ajax("loadScripts", new Array(), function() {
                $("#customBox").height($(window).height()-150)

                $.custom().then(({custom,C_DataSource,C_Where,C_Grid})=>{
                    ins_argjson.custom = custom;
                    ins_argjson.C_DataSource = C_DataSource;
                    ins_argjson.C_Where = C_Where;
                    ins_argjson.C_Grid = C_Grid;

                    let scrname = ins_argjson.scrname;
                    let params = {"jn":JSON.stringify({"arg":{"scrname":scrname}})};
                    ins_argjson.C_DataSource.ScreenBizData = ins_argjson.C_DataSource.getScreenBizDefault(params)
                    let ScreenData = ins_argjson.C_DataSource.ScreenBizData

                    var text = ScreenData.screen[0]['title']||'自定义页面'
                    $("title").text(text)

                    var param = {}
                    param.boxId = "#customBox"  //自定义DIV
                    param.onlyInitComponent = 'yes' //仅加载组件
                    custom.init(ScreenData,param,function(){
                        
                    })
                }).then(()=>{

                })
            })
        <\/script>
    </body>
</html>
`
                //statement+formatHtmlText(a+data)+z
        return formatHtmlText(data)
    }

    function formatHtmlText(htmltext) {
        var p1 = /([A-Za-z])((<[^<]*>)*[\u4e00-\u9fa5]+)/gi;
        var r = htmltext
        r = r.replace(p1, "$1 $2");
        //匹配数字临近中文
        var p2 = /([0-9])([\u4e00-\u9fa5]+)/gi;
        r = r.replace(p2, "$1 $2");
        //匹配中文临近数字
        var p3 = /([\u4e00-\u9fa5]+)([0-9])/gi;
        r = r.replace(p3, "$1 $2");
   
        var p4 = /([\u4e00-\u9fa5]+(<[^<]*>)*)([A-Za-z])/gi;
        r = r.replace(p4, "$1 $3");
        //r = r.replace("） ", "）");

        var strs = r;
        var left = null;
        var right = null;
        var str = "";
        var blank = "\t";
        var fmt = [];
   
        for (var i = 0; i <strs.length; i++) {
          //发现左尖括号后将其位置记录在left变量上
          if (strs[i] == "<") {
            left = i;
          } else if (strs[i] == ">") {
            //发现右尖括号后将其记录在right变量上
            right = i;
          }
          //当做尖括号右尖括号都记录了一个位置后，说明二者之间的内容为代码的一行
          if (typeof left == "number" && typeof right == "number") {
            //判断字符串左尖括号后是否为‘/’，如果满足，表明该行代码为双标签的闭合标签
            if (strs[left + 1] == "/") {
              //对数组中的空格做出栈，确保代码缩进正确
              fmt.pop();
              //将该行代码放入str变量中
              str += fmt.join("") + strs.slice(left, right + 1);
              //判断字符串右尖括号前一位是否为‘/’，如满足，表明该标签为严格闭合的单标签
            } else if (strs[right - 1] == "/") {
              str += fmt.join("") + strs.slice(left, right + 1);
              //判断字符串开头是否包含input/imig/hr/br/link/meta等字母，用于屏蔽非严格未闭合的单标签
            } else if (
              strs
                .slice(left, right)
                .search(/\<input|\<img|\<hr|\<br|\<link|\<meta/) != -1
            ) {
              str += fmt.join("") + strs.slice(left, right + 1);
              //对双标签的左标签进行的操作
            } else {
              str += fmt.join("") + strs.slice(left, right + 1);
              //向数组中堆入一个空格，确保下一行双标签的左标签的缩进正确
              fmt.push(blank);
            }
            //对 right 位置后的字符串进行遍历
            for (var j = right; j < strs.length; j++) {
              //查找right位置后，第一个左尖括号的位置，二者之间的内容即为代码中的文本内容
              if (strs[j] == "<") {
                //去掉文本中多余的空格
                var s = strs.slice(right + 1, j).replace(/\s*/g, "");
                if (s) {
                  // 当文本中去掉空格后任然有内容，则将文本拼入 str 变量进行存储
                  str += s;
                }
                break;
              }
            }
            // 每次获得一次左右尖括号的位置后，即得到了一行代码，为代码做换行处理
            str += "\n";
            // 重置 left、right 的值，用于 for 循环的下次存储做右尖括号的位置
            left = null;
            right = null;
          }
        }
        // 返回得到的格式化完成的 html 代码字符串
        return str;
      }
